//
//  WH_LoginView.m
//  App_6.23
//
//  Created by wanghao on 16/7/13.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_LoginView.h"
#import "AlertControllerUtility.h"

@interface WH_LoginView ()<FBSDKLoginButtonDelegate>

@property (nonatomic, strong) UITextField *userName;

@property (nonatomic, strong) UITextField *passWord;

@property (nonatomic, copy) NSString *fbEmailID;

@end
@implementation WH_LoginView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubViews];
        
    }
    return self;
}

- (void)createSubViews{
    
    self.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    CGFloat x = width / 2;
    CGFloat y = height / 3;
    
#pragma mark 输入框 1010 1011
    UIView *textView = [[UIView alloc] init];
    textView.backgroundColor = [UIColor whiteColor];
    textView.center = CGPointMake(x, y);
    [textView.layer setBorderWidth:1.5];
    [textView.layer setBorderColor:[UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1].CGColor];
    UIView *aview = [[UIView alloc] initWithFrame:CGRectMake(65, 45, 300, 1)];
    aview.backgroundColor = [UIColor colorWithWhite:0.851 alpha:1.000];
    [textView addSubview:aview];
    [self addSubview:textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@-1);
        make.top.mas_equalTo(@200);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(@91);
    }];
    
    _userName = [[UITextField alloc] init];
    [textView addSubview:_userName];
    [_userName mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@75);
        make.top.mas_equalTo(@0);
        make.right.mas_equalTo(@0);
        make.height.mas_equalTo(@45);
    }];
    
    _passWord = [[UITextField alloc] init];
    [textView addSubview:_passWord];
    [_passWord mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@75);
        make.top.mas_equalTo(@46);
        make.right.mas_equalTo(@-70);
        make.height.mas_equalTo(@45);
    }];
    
    NSArray *array = [NSArray arrayWithObjects:@" 手机/邮箱", @" 密码", @"iconfont-zhanghao", @"iconfont-mima", nil];
    NSArray *textFieldArr = [NSArray arrayWithObjects:_userName, _passWord, nil];
    
    for (int i = 0; i < 2; i++) {
        
        UIImageView *textImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:array[2 + i]]];
        textImage.frame = CGRectMake(25, 10 + 45 * i, 25, 25);
        [textView addSubview:textImage];
        
        UITextField *textfield = textFieldArr[i];
        textfield.placeholder = array[i];
        if (i == 1) {
            textfield.secureTextEntry = YES;
        }
    }
    
#pragma mark 登录键 1003
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    but.frame = CGRectMake(39, 297, 300, 45);
    but.tag = 1003;
    but.backgroundColor = [UIColor colorWithRed:0.082 green:0.565 blue:0.847 alpha:1.000];
    [but.layer setCornerRadius:4];
    [but setTitle:@"登陆" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:but];
    
    [but mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(40*HEI_ONE);
        make.top.mas_equalTo(297);
        
    }];
    UIButton *regist = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:regist];
    regist.backgroundColor =[UIColor colorWithRed:0.082 green:0.565 blue:0.847 alpha:1.000];
    [regist.layer setCornerRadius:4];
    [regist mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@10);
        make.top.equalTo(but.mas_bottom).offset(5);
        make.height.mas_equalTo(40*HEI_ONE);
        make.right.mas_equalTo(@-10);
    }];
    [regist setTitle:@"注册" forState:UIControlStateNormal];
    [regist addTarget:self action:@selector(registAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *forget = [UIButton buttonWithType:UIButtonTypeCustom];
    [textView addSubview:forget];
    [forget mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.height.equalTo(_passWord);
        make.left.equalTo(_passWord.mas_right);
        make.right.mas_equalTo(0);
        
    }];
    forget.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [forget setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forget setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [forget addTarget:self action:@selector(forgetAction:) forControlEvents:UIControlEventTouchUpInside];
    

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    loginButton.tooltipBehavior = FBSDKLoginButtonTooltipBehaviorForceDisplay;
    loginButton.loginBehavior = FBSDKLoginBehaviorWeb;
    loginButton.readPermissions = @[@"public_profile", @"email", @"user_friends"];
    [self addSubview:loginButton];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(regist.mas_bottom).offset(5);
        make.height.mas_equalTo(40*HEI_ONE);
    }];
}

#pragma mark - FBSDKLoginButtonDelegate

- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error
{
    UIAlertController *alertController;
    if (error) {
        alertController = [AlertControllerUtility alertControllerWithTitle:@"Login Fail"
                                                                   message:[NSString stringWithFormat:@"Login fail with error: %@", error]];
    } else if (!result || result.isCancelled) {
        alertController = [AlertControllerUtility alertControllerWithTitle:@"Login Cancelled"
                                                                   message:@"User cancelled login"];
    } else {
        alertController = [AlertControllerUtility alertControllerWithTitle:@"Login Success"
                                                                   message:[NSString stringWithFormat:@"Login success with granted permission: %@", [[result.grantedPermissions allObjects] componentsJoinedByString:@" "]] ];
        

        [[[FBSDKGraphRequest alloc]initWithGraphPath:@"me" parameters:nil]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
            //id = 1525628844432683;
            //            name = "\U9ec4\U6743\U6d69"
            NSLog(@"fetched user:%@", result);
            self.fbEmailID = [NSString stringWithFormat:@"%@@facebook.com",[result objectForKey:@"id"]];
        
            if ([result objectForKey:@"id"] != nil) {
                //先注册后登录
                [self registWithPassWord:@"12345678" repassWord:@"12345678" iphone:@"15104659248" userName:self.fbEmailID];

            }
        }];
    
    }
}
- (void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton
{
    
    
}

#pragma mark - 注册&&登录

-(void)registWithPassWord:(NSString *)passWord repassWord:(NSString *)repassWord iphone:(NSString *)iphone userName:(NSString *)userName{
    
    NSString *body = [NSString stringWithFormat:@"action=user_reg&user_name=%@&pwd=%@&pwd2=%@&token=%@",userName,passWord,repassWord,iphone];
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        //NSString *message = [dic objectForKey:@"message"];
        if ([status isEqualToString:@"success"]){
            
            NSLog(@"注册---%@",result);
            [WSProgressHUD showImage:nil status:@"注册成功"];
            
            [self.delegate loginWithUserName:self.fbEmailID passWord:@"12345678"];
            
        }else{
            
            //[WSProgressHUD showImage:nil status:message];
            [self.delegate loginWithUserName:self.fbEmailID passWord:@"12345678"];

        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
}

- (void)registAction:(UIButton *)button {
    
    [self.delegate pushRegistViewController];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    for (int i = 0; i < 2; i++) {
        UITextField *textField = (UITextField *)[self viewWithTag:1010 + i];
        if (textField.isFirstResponder) {
            [textField resignFirstResponder];
        }
    }
    
}

- (void)loginAction:(UIButton *)send {
    
    if ([_userName.text isEqualToString:@""] || [_passWord.text isEqualToString:@""]) {
        [WSProgressHUD showImage:nil status:@"账号或密码为空"];
        return;
    }
    else {
        
        [self.delegate loginWithUserName:_userName.text passWord:_passWord.text];
    }
}

-(void)forgetAction:(UIButton *)forget{
    
    
    [self.delegate pushForgetViewController];
}
@end
